package com.blb.zy_community.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.blb.zy_community.entity.*;
import com.blb.zy_community.mapper.SysUserPostMapper;
import com.blb.zy_community.service.ISysUserService;
import com.blb.zy_community.service.impl.*;
import net.sf.jsqlparser.expression.LongValue;
import org.apache.logging.log4j.message.Message;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.*;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.blb.zy_community.entity.ResponseResult;
import com.blb.zy_community.entity.SysUser;
import com.blb.zy_community.service.impl.SysUserServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.stereotype.Controller;

import java.io.Console;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 用户信息表 前端控制器
 * </p>
 *
 * @author 二组
 * @since 2023-06-18
 */
@CrossOrigin
@RestController
public class SysUserController {
    @Autowired
    private SysUserServiceImpl sysUserService;

    @Autowired
    private SysRoleServiceImpl sysRoleService;
    @Autowired
    private SysPostServiceImpl sysPostService;
    @Autowired
    private BCryptPasswordEncoder bCryptPasswordEncoder;

    @Autowired
    private SysUserRoleServiceImpl sysUserRoleService;
    @Autowired
    private SysUserPostServiceImpl sysUserPostService;




    @GetMapping("user-page")
    public ResponseResult<Page<SysUser>> findById(@RequestParam(required = false, defaultValue = "1") Long current,
                                                  @RequestParam(required = false, defaultValue = "5") Long size,
                                                  @RequestParam(required = false, defaultValue = "") String userName) {
        Page<SysUser> sysUserPage = sysUserService.GetUserById(current, size, userName);
        System.out.println(sysUserPage);
        return ResponseResult.ok(sysUserPage);
    }

    @PutMapping("/userForPic")
    public ResponseResult<String> addUser(@RequestBody SysUser sysUser) {
        sysUserService.updateById(sysUser);
        return ResponseResult.ok(sysUser);
    }

    @DeleteMapping("/user/{id}")
    public ResponseResult<String> deleteUser(@PathVariable Long id) {
        sysUserService.removeById(id);
        return ResponseResult.ok(id);
    }

    @PutMapping("/user")
    public ResponseResult<String> updataUser(@RequestBody SysUser sysUser) {

//        SysUser sysUser1 = new SysUser();
        String password = sysUser.getPassword();
        String encode = bCryptPasswordEncoder.encode(password);
        sysUser.setPassword(encode);
        sysUserService.updateById(sysUser);
        return ResponseResult.ok(sysUser);
    }
    @PutMapping("/user2")
    public ResponseResult<String> updataUser2(@RequestBody SysUser sysUser) {

        sysUserService.updateById(sysUser);
        return ResponseResult.ok(sysUser);
    }


    @GetMapping("/checkPwd")
    public ResponseResult<String> getPwd(@RequestParam("oldPassword") String eXPassword, @RequestParam("userId") String userId) {

        SysUser user = sysUserService.getById(userId);
        //        待判断
        boolean matches = bCryptPasswordEncoder.matches(eXPassword, user.getPassword());
        //数据库里的密码
        if (matches){
            return ResponseResult.ok("");
        }else {
            return ResponseResult.ok("原密码输入错误");
        }
    }

    /**
     * 注册
     * @param sysUser
     * @return
     */
    @PostMapping("/register")
    public ResponseResult<String> newRegister(@RequestBody SysUser sysUser){
        sysUserService.save(sysUser);
        return ResponseResult.ok(sysUser);
    }



    /**
     * 获取用户列表分页
     * @param current
     * @param size
     * @return
     */
    @GetMapping("/sysUser-page2")
    public ResponseResult<SysUser> getSysUserPage2(@RequestParam(required = false, defaultValue = "1") Long current,
                                                  @RequestParam(required = false, defaultValue = "5") Long size,
                                                  @RequestParam(required = false, defaultValue = "") String userName,
                                                  @RequestParam(required = false, defaultValue = "") String phonenumber,
                                                  @RequestParam(required = false, defaultValue = "") String status,
                                                  @RequestParam(required = false) String[] timeDate,
                                                  @RequestParam(required = false) Long deptId) {
        String startTime = "";
        String endTime = "";
        if (timeDate != null && timeDate.length != 0) {
            boolean isEmpty = false;
            for (int i = 0; i < timeDate.length; i++) {
                if (timeDate[i].equals("null")) {
                    isEmpty = true;
                    break;
                }
            }
            if (!isEmpty) {
                startTime = timeDate[0];
                endTime = timeDate[1];
            }
        }

//        Page<SysUser> sysUserPage = sysUserService.SelectSysUserPage(new Page<>(current, size), userName, phonenumber, status, startTime, endTime, deptId);
        Page<SysUser> sysUserPage =sysUserService.selectSysUserPage2(new Page<>(current, size), userName, phonenumber, status, startTime, endTime, deptId);
        String jsonString = JSON.toJSONString(sysUserPage);
        System.out.println("用户-----------------------");
        System.out.println(jsonString);
        return ResponseResult.ok(sysUserPage);
    }

    /**
     * 获取用户列表分页
     * @param current
     * @param size
     * @return
     */
    @GetMapping("/sysUser-page")
    public ResponseResult<SysUser> getSysUserPage(@RequestParam(required = false, defaultValue = "1") Long current,
                                                  @RequestParam(required = false, defaultValue = "5") Long size,
                                                  @RequestParam(required = false, defaultValue = "") String userName,
                                                  @RequestParam(required = false, defaultValue = "") String phonenumber,
                                                  @RequestParam(required = false, defaultValue = "") String status,
                                                  @RequestParam(required = false) String[] timeDate,
                                                  @RequestParam(required = false) Long deptId) {
        String startTime = "";
        String endTime = "";
        if (timeDate != null && timeDate.length != 0) {
            boolean isEmpty = false;
            for (int i = 0; i < timeDate.length; i++) {
                if (timeDate[i].equals("null")) {
                    isEmpty = true;
                    break;
                }
            }
            if (!isEmpty) {
                startTime = timeDate[0];
                endTime = timeDate[1];
            }
        }

        Page<SysUser> sysUserPage = sysUserService.SelectSysUserPage(new Page<>(current, size), userName, phonenumber, status, startTime, endTime, deptId);
        return ResponseResult.ok(sysUserPage);
    }


    /**
     * 用户管理-新增
     *
     * @return
     */
    @PostMapping("/sysUser")
    public ResponseResult<String> addUserRoleAndPost(@RequestBody Map<String, Object> param) {
        Object user = param.get("user");
        Object roleId = param.get("roleId");
        Object postId = param.get("postId");

        SysUser sysUser = JSON.parseObject(JSON.toJSONString(user), new TypeReference<SysUser>() {
        });
        List<Long> roleIds = JSON.parseObject(JSON.toJSONString(roleId), new TypeReference<List<Long>>() {
        });
        List<Long> postIds = JSON.parseObject(JSON.toJSONString(postId), new TypeReference<List<Long>>() {
        });
        String encode = bCryptPasswordEncoder.encode(sysUser.getPassword());
        sysUser.setCreateTime(LocalDateTime.now());
        sysUser.setPassword(encode);
        sysUserService.addUserRoleAndPost(sysUser, postIds, roleIds);
        return ResponseResult.ok(param);
    }

    /**
     * 根据用户名查询系统用户
     *
     * @param username
     * @return
     */
    @GetMapping("/sysUser/{username}")
    public ResponseResult<SysUser> getSysUserByUsername(@PathVariable("username") String username) {
        SysUser sysUser = sysUserService.getOne(new QueryWrapper<SysUser>().eq("user_name", username));
        return ResponseResult.ok(sysUser);

    }

    /**
     * 修改用户状态
     */
    @PutMapping("/user-status/{userId}")
    public ResponseResult<String> updateStatus(@PathVariable Long userId) {

        SysUser sysUser = sysUserService.getOne(new QueryWrapper<SysUser>().eq("user_id", userId));
        String status = "0";
        if ("0".equals(sysUser.getStatus())) {
            status = "1";
        }
        sysUserService.updateStatus(Long.valueOf(status), userId);
        return ResponseResult.ok(status);
    }

    /**
     * 批量删除--根据用户id
     *
     * @param
     * @return
     */
    @DeleteMapping("/sysUsers/{userIds}")
    public ResponseResult<String> deleteUsers(@PathVariable Long[] userIds) {
        sysUserService.deleteSysUserIds(userIds);
        return ResponseResult.ok(userIds);
    }

    /**
     * 操作--删除
     *
     * @param userId
     * @return
     */
    @DeleteMapping("/sysUser/{userId}")
    public ResponseResult<String> deleteSysUser(@PathVariable Long userId) {
        sysUserService.removeById(userId);
        return ResponseResult.ok(userId);
    }

    /**
     * 用户管理-修改
     *
     * @param param
     * @return
     */
    @PutMapping("/updateUser")
    public ResponseResult<String> updateUserRoleAndPost(@RequestBody Map<String, Object> param) {
        Object user = param.get("user");
        Object roleId = param.get("roleId");
        Object postId = param.get("postId");

        SysUser sysUser = JSON.parseObject(JSON.toJSONString(user), new TypeReference<SysUser>() {
        });
        List<Long> RoleIds = JSON.parseObject(JSON.toJSONString(roleId), new TypeReference<List<Long>>() {
        });
        List<Long> PostIds = JSON.parseObject(JSON.toJSONString(postId), new TypeReference<List<Long>>() {
        });
        sysUser.setCreateTime(LocalDateTime.now());
        sysUserService.updateUserRoleAndPost(sysUser, RoleIds, PostIds);
        return ResponseResult.ok(sysUser);
    }

    /**
     * 重置密码
     *
     * @return
     */
    @PutMapping("userPwd/{userId}/{password}")
    public ResponseResult<String> updatePwd(@PathVariable Long userId, @PathVariable String password) {
        String encode = bCryptPasswordEncoder.encode(password);
        sysUserService.updatePwd(userId, encode);
        return ResponseResult.ok(userId);
    }

    @GetMapping("/checkUserNameSame/{username}")
    public ResponseResult<Boolean> checkUserNameSame(@PathVariable("username") String username){

        SysUser sysUser = sysUserService.getOne(new QueryWrapper<SysUser>().eq("user_name", username));
        if (sysUser==null){
            return ResponseResult.ok(false);
        }else {
            return ResponseResult.ok(true);
        }

    }


}
